package com.fly.springbootTemplate.serviceImpl;

import com.fly.springbootTemplate.dao.StudentDao;
import com.fly.springbootTemplate.dao.StudentDetailDao;
import com.fly.springbootTemplate.entity.Student;
import com.fly.springbootTemplate.entity.dto.StudentDto;
import com.fly.springbootTemplate.service.StudentDetailService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class StudentDetailServiceImpl implements StudentDetailService {

    @Autowired
    private StudentDetailDao studentDetailDao;
    @Autowired
    private StudentDao studentDao;
    @Override
    public boolean addStudentDetail(StudentDto studentDto) {
        //dto存放所有的数据，dto中的数据可以完全覆盖详情表
        boolean flag = studentDetailDao.insertStudentDetail(studentDto);
        if (flag) {
            Student studentInsert = new Student();
            //剩下的dto部分可以完全覆盖Student表
            BeanUtils.copyProperties(studentDto, studentInsert);
            return studentDao.insertStudent(studentInsert);
        }
        return false;
    }

    @Override
    public boolean deleteStudentDetail(Integer sno) {
        //用sno先删除详情表中的对应sno的数据
        boolean flag = studentDetailDao.deleteStudentDetail(sno);
        if (flag) {
            return studentDao.deleteStudent(sno);
        }
        return false;
    }

    @Override
    public boolean updateStudentDetail(StudentDto studentDto) {
        //先更新详情表，dto中的数据可以完全更新详情表
        boolean flag = studentDetailDao.updateStudentDetail(studentDto);
        if (flag){
            Student studentUpdate = new Student();
            //剩下的dto部分可以完全覆盖Student表
            //
            BeanUtils.copyProperties(studentDto, studentUpdate);
            return studentDao.updateStudent(studentUpdate);
        }
        return false;
    }

    @Override
    public List<StudentDto> getAllStudentDetail() {
//        List<Student> studentList = studentDao.selectAllStudent();
//        List<StudentDto> studentDetailList = studentDetailDao.selectAllStudentDetail();
//        List<StudentDto> studentDtoList = new ArrayList<>();
//        for (Student student : studentList) {
//            for (StudentDto studentDto : studentDetailList) {
//                if (student.getSno().equals(studentDto.getSno())) {
//                    //把第一个student加进去把元素从列表中取出来，然后放到dtoList中
//                    studentDtoList.add(studentDto);
//                    //把元素从列表中取出来，然后放到dtoList中
//                }
//            }
//        }
        return studentDetailDao.selectAllStudentDetail();
    }

    @Override
    public StudentDto getStudentDetailBySno(Integer sno) {
        return studentDetailDao.selectStudentDetailBySno(sno);
    }
}
